<template>
  <div class="stock-list">
    <h2>股票管理</h2>
    
    <!-- 同步股票数据按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="syncStocks" :loading="syncLoading">
        从AkShare同步股票数据
      </el-button>
      <el-button type="success" @click="showAddDialog">添加股票</el-button>
    </div>
    
    <!-- 股票列表表格 -->
    <el-table :data="stocks" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="symbol" label="股票代码" width="150"></el-table-column>
      <el-table-column prop="name" label="股票名称" width="200"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="showHistory(scope.row)">查看历史数据</el-button>
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteStock(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next"
      @current-change="handlePageChange"
      class="pagination"
    />
    
    <!-- 添加/编辑股票对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
      <el-form :model="currentStock" ref="stockForm">
        <el-form-item label="股票代码" :label-width="formLabelWidth">
          <el-input v-model="currentStock.symbol" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="股票名称" :label-width="formLabelWidth">
          <el-input v-model="currentStock.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStock">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 历史数据对话框 -->
    <el-dialog title="历史数据" v-model="historyDialogVisible" width="80%">
      <div v-if="historyData.length > 0">
        <el-table :data="historyData" height="400" style="width: 100%">
          <el-table-column prop="date" label="日期" width="120"></el-table-column>
          <el-table-column prop="open" label="开盘价"></el-table-column>
          <el-table-column prop="high" label="最高价"></el-table-column>
          <el-table-column prop="low" label="最低价"></el-table-column>
          <el-table-column prop="close" label="收盘价"></el-table-column>
          <el-table-column prop="volume" label="成交量"></el-table-column>
        </el-table>
      </div>
      <div v-else>
        <p>暂无历史数据</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="historyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'StockList',
  data() {
    return {
      stocks: [],
      loading: false,
      syncLoading: false,
      currentPage: 1,
      pageSize: 100,
      total: 0,
      dialogVisible: false,
      historyDialogVisible: false,
      dialogTitle: '',
      formLabelWidth: '80px',
      currentStock: {
        id: null,
        symbol: '',
        name: ''
      },
      historyData: [],
      isEditing: false
    }
  },
  mounted() {
    this.loadStocks()
  },
  methods: {
    // 加载股票列表
    async loadStocks() {
      this.loading = true
      try {
        const response = await axios.get(`/api/stocks`, {
          params: {
            skip: (this.currentPage - 1) * this.pageSize,
            limit: this.pageSize
          }
        })
        this.stocks = response.data
        // 这里简化处理，实际应该从后端获取总数
        this.total = response.data.length
      } catch (error) {
        this.$message({
          message: '获取股票列表失败: ' + error.message,
          type: 'error'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 同步股票数据
    async syncStocks() {
      this.syncLoading = true
      try {
        const response = await axios.post(`/api/stocks/sync`)
        this.$message({
          message: `同步成功，共更新${response.data.length}只股票`,
          type: 'success'
        })
        this.loadStocks()
      } catch (error) {
        this.$message({
          message: '同步失败: ' + error.response?.data?.detail || error.message,
          type: 'error'
        })
      } finally {
        this.syncLoading = false
      }
    },
    
    // 显示添加对话框
    showAddDialog() {
      this.currentStock = { id: null, symbol: '', name: '' }
      this.dialogTitle = '添加股票'
      this.isEditing = false
      this.dialogVisible = true
    },
    
    // 显示编辑对话框
    showEditDialog(stock) {
      this.currentStock = { ...stock }
      this.dialogTitle = '编辑股票'
      this.isEditing = true
      this.dialogVisible = true
    },
    
    // 保存股票（添加或更新）
    async saveStock() {
      try {
        if (this.isEditing) {
          // 更新股票
          await axios.put(`/api/stocks/${this.currentStock.id}`, {
            name: this.currentStock.name
          })
          this.$message({
            message: '更新成功',
            type: 'success'
          })
        } else {
          // 添加股票
          await axios.post(`/api/stocks`, {
            symbol: this.currentStock.symbol,
            name: this.currentStock.name
          })
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        }
        this.dialogVisible = false
        this.loadStocks()
      } catch (error) {
        this.$message({
          message: '操作失败: ' + (error.response?.data?.detail || error.message),
          type: 'error'
        })
      }
    },
    
    // 删除股票
    async deleteStock(stock) {
      try {
        await this.$confirm(`确定要删除股票 ${stock.name} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await axios.delete(`/api/stocks/${stock.id}`)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.loadStocks()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message({
            message: '删除失败: ' + (error.response?.data?.detail || error.message),
            type: 'error'
          })
        }
      }
    },
    
    // 显示历史数据
    async showHistory(stock) {
      try {
        const response = await axios.get(`/api/stocks/${stock.id}/history`)
        this.historyData = response.data.data || []
        this.historyDialogVisible = true
      } catch (error) {
        this.$message({
          message: '获取历史数据失败: ' + (error.response?.data?.detail || error.message),
          type: 'error'
        })
      }
    },
    
    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page
      this.loadStocks()
    }
  }
}
</script>

<style scoped>
.stock-list {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>